package org.apache.rocketmq.store;

import org.apache.rocketmq.common.UtilAll;
import org.apache.rocketmq.common.constant.LoggerName;
import org.apache.rocketmq.logging.org.slf4j.Logger;
import org.apache.rocketmq.logging.org.slf4j.LoggerFactory;
import org.apache.rocketmq.store.logfile.DefaultMappedFile;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @课程描述:从零带你写框架系列中的课程，整个系列包含netty，xxl-job，rocketmq，nacos，sofajraft，spring，springboot，disruptor，编译器，虚拟机等等。
 * @author：陈清风扬，个人微信号：chenqingfengyangjj。
 * @date:2025/6/29
 * @方法描述：消息检查点信息对象，这个对象就是用来更新消息刷新信息检查点文件的内容的
 */
public class StoreCheckpoint {

    private static final Logger log = LoggerFactory.getLogger(LoggerName.STORE_LOGGER_NAME);

    //随机访问文件对象，用于对检查点文件进行读写操作
    private final RandomAccessFile randomAccessFile;

    //文件通道
    private final FileChannel fileChannel;

    //内存映射缓冲区，将文件内容直接映射到内存，提供高性能的文件访问方式
    private final MappedByteBuffer mappedByteBuffer;

    //CommitLog文件最后存储消息的时间
    private volatile long physicMsgTimestamp = 0;

    //消费队列最后存储消息的时间
    private volatile long logicsMsgTimestamp = 0;

    //索引文件最后存储消息的时间
    private volatile long indexMsgTimestamp = 0;

    //主节点消息刷盘偏移量
    private volatile long masterFlushedOffset = 0;

    //已确认消息偏移量
    private volatile long confirmPhyOffset = 0;


    /**
     * @课程描述:从零带你写框架系列中的课程，整个系列包含netty，xxl-job，rocketmq，nacos，sofajraft，spring，springboot，disruptor，编译器，虚拟机等等。
     * @author：陈清风扬，个人微信号：chenqingfengyangjj。
     * @方法描述：构造方法
     */
    public StoreCheckpoint(final String scpPath) throws IOException {
        //根据路径创建文件对象
        File file = new File(scpPath);
        //确保文件所在目录存在，如果不存在则创建
        UtilAll.ensureDirOK(file.getParent());
        //判断文件是否已经存在
        boolean fileExists = file.exists();
        //创建随机访问文件对象，rw表示读写模式
        this.randomAccessFile = new RandomAccessFile(file, "rw");
        //获取文件通道，用于后续的内存映射操作
        this.fileChannel = this.randomAccessFile.getChannel();
        //将文件映射到内存中，使用读写模式，从文件起始位置开始，映射大小为一个操作系统页面，也就是4KB
        this.mappedByteBuffer = fileChannel.map(FileChannel.MapMode.READ_WRITE, 0, DefaultMappedFile.OS_PAGE_SIZE);
        //如果文件已存在，则从文件中读取之前保存的检查点信息
        if (fileExists) {
            //以下操作都很简单，大家自己看看就行，我就不添加详细注释了
            log.info("store checkpoint file exists, " + scpPath);
            this.physicMsgTimestamp = this.mappedByteBuffer.getLong(0);
            this.logicsMsgTimestamp = this.mappedByteBuffer.getLong(8);
            this.indexMsgTimestamp = this.mappedByteBuffer.getLong(16);
            this.masterFlushedOffset = this.mappedByteBuffer.getLong(24);
            this.confirmPhyOffset = this.mappedByteBuffer.getLong(32);
            log.info("store checkpoint file physicMsgTimestamp " + this.physicMsgTimestamp + ", "
                    + UtilAll.timeMillisToHumanString(this.physicMsgTimestamp));
            log.info("store checkpoint file logicsMsgTimestamp " + this.logicsMsgTimestamp + ", "
                    + UtilAll.timeMillisToHumanString(this.logicsMsgTimestamp));
            log.info("store checkpoint file indexMsgTimestamp " + this.indexMsgTimestamp + ", "
                    + UtilAll.timeMillisToHumanString(this.indexMsgTimestamp));
            log.info("store checkpoint file masterFlushedOffset " + this.masterFlushedOffset);
            log.info("store checkpoint file confirmPhyOffset " + this.confirmPhyOffset);
        } else {
            //如果文件不存在，则记录相应的日志信息
            log.info("store checkpoint file not exists, " + scpPath);
        }
    }


    /**
     * @课程描述:从零带你写框架系列中的课程，整个系列包含netty，xxl-job，rocketmq，nacos，sofajraft，spring，springboot，disruptor，编译器，虚拟机等等。
     * @author：陈清风扬，个人微信号：chenqingfengyangjj。
     * @方法描述：终止检查点工作的方法
     */
    public void shutdown() {
        //调用flush方法将最新的检查点信息刷新到本地硬盘
        this.flush();
        //清理内存映射缓冲区，释放相关资源
        UtilAll.cleanBuffer(this.mappedByteBuffer);
        //关闭文件通道
        try {
            this.fileChannel.close();
        } catch (IOException e) {
            log.error("Failed to properly close the channel", e);
        }
    }


    /**
     * @课程描述:从零带你写框架系列中的课程，整个系列包含netty，xxl-job，rocketmq，nacos，sofajraft，spring，springboot，disruptor，编译器，虚拟机等等。
     * @author：陈清风扬，个人微信号：chenqingfengyangjj。
     * @方法描述：刷新信息到本地硬盘的方法
     */
    public void flush() {
        this.mappedByteBuffer.putLong(0, this.physicMsgTimestamp);
        this.mappedByteBuffer.putLong(8, this.logicsMsgTimestamp);
        this.mappedByteBuffer.putLong(16, this.indexMsgTimestamp);
        this.mappedByteBuffer.putLong(24, this.masterFlushedOffset);
        this.mappedByteBuffer.putLong(32, this.confirmPhyOffset);
        this.mappedByteBuffer.force();
    }

    public long getPhysicMsgTimestamp() {
        return physicMsgTimestamp;
    }

    public void setPhysicMsgTimestamp(long physicMsgTimestamp) {
        this.physicMsgTimestamp = physicMsgTimestamp;
    }

    public long getLogicsMsgTimestamp() {
        return logicsMsgTimestamp;
    }

    public void setLogicsMsgTimestamp(long logicsMsgTimestamp) {
        this.logicsMsgTimestamp = logicsMsgTimestamp;
    }

    public long getConfirmPhyOffset() {
        return confirmPhyOffset;
    }

    public void setConfirmPhyOffset(long confirmPhyOffset) {
        this.confirmPhyOffset = confirmPhyOffset;
    }

    public long getMinTimestampIndex() {
        return Math.min(this.getMinTimestamp(), this.indexMsgTimestamp);
    }

    public long getMinTimestamp() {
        long min = Math.min(this.physicMsgTimestamp, this.logicsMsgTimestamp);

        min -= 1000 * 3;
        if (min < 0) {
            min = 0;
        }

        return min;
    }

    public long getIndexMsgTimestamp() {
        return indexMsgTimestamp;
    }

    public void setIndexMsgTimestamp(long indexMsgTimestamp) {
        this.indexMsgTimestamp = indexMsgTimestamp;
    }

    public long getMasterFlushedOffset() {
        return masterFlushedOffset;
    }

    public void setMasterFlushedOffset(long masterFlushedOffset) {
        this.masterFlushedOffset = masterFlushedOffset;
    }
}

